/*
 * All right reserved@Raygo 2022~2030
 */

package com.raygo.runner.core.command;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.raygo.runner.core.annotation.CmdDefine;
import com.raygo.runner.core.entity.FlowContext;

/**
 * IF 命令
 *
 * @author Raygo
 * @since 2022年8月6日
 */
@CmdDefine(name = "If", desc = "条件判断命令")
public class IfCommand implements Command {
    @Override
    public CmdResult runCommand(Map<String, Object> input, FlowContext context) throws CmdException {
        String type = (String) input.get("type");
        String left = input.get("left").toString();
        String operator = (String) input.get("operator");
        String right = input.get("right").toString();
        boolean result = false;
        switch (type) {
        case "String": {
            switch (operator) {
            case "==":
                result = left.equals(right);
                break;
            case "!=":
                result = !left.equals(right);
                break;
            default:
                throw new CmdException("Unexpected operator: " + operator);
            }
        }
            break;
        case "Integer": {
            switch (operator) {
            case "==":
                result = (Integer.parseInt(left) == Integer.parseInt(right));
                break;
            case "!=":
                result = (Integer.parseInt(left) != Integer.parseInt(right));
                break;
            case "<=":
                result = (Integer.parseInt(left) <= Integer.parseInt(right));
                break;
            case ">=":
                result = (Integer.parseInt(left) >= Integer.parseInt(right));
                break;
            default:
                throw new CmdException("Unexpected operator: " + operator);
            }
        }
            break;
        case "Boolean": {
            result = left.equalsIgnoreCase("true");
        }
            break;
        default:
            throw new CmdException("Unexpected type: " + type);
        }
        return new CmdResult("result", result);
    }

    @Override
    public List<CmdParam<?>> getInputParam() {
        List<CmdParam<?>> inputCmdParams = new ArrayList<>();
        inputCmdParams.add(new CmdParam<String>("type", "String", "数据类型").setOption("String", "Integer", "Boolean"));
        inputCmdParams.add(new CmdParam<String>("left", "Hello"));
        inputCmdParams.add(new CmdParam<String>("operator", "=="));
        inputCmdParams.add(new CmdParam<String>("right", "World"));
        return inputCmdParams;
    }

    @Override
    public List<CmdParam<?>> getOutputParam() {
        List<CmdParam<?>> inputCmdParams = new ArrayList<>();
        inputCmdParams.add(new CmdParam<Boolean>("result", false));
        return inputCmdParams;
    }
}
